<template>
    <div class="box">
        <div class="title">
            {{ routeMsg ?'修改':'添加' }}
        </div>
        <div class="frombox">
            <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                status-icon
                :rules="rules"
                label-width="120px"
                class="demo-ruleForm"
            >
                <el-form-item label="标题" >
                    <el-input v-model="ruleForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="关键字" >
                    <el-input v-model="ruleForm.keywords" autocomplete="off" />
                </el-form-item>
                <el-form-item label="作者">
                    <el-input v-model="ruleForm.author" autocomplete="off" />
                </el-form-item>
                <el-form-item label="介绍" >
                    <el-input v-model="ruleForm.desc" type="textarea" />
                </el-form-item>
                <el-form-item label="缩略图">
                    <el-upload action="#" list-type="picture-card" :auto-upload="false">
                        <el-icon><Plus /></el-icon>

                        <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                            <span
                                class="el-upload-list__item-preview"
                                @click="handlePictureCardPreview(file)"
                            >
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span
                                v-if="!disabled"
                                class="el-upload-list__item-delete"
                                @click="handleDownload(file)"
                            >
                                <el-icon><Download /></el-icon>
                            </span>
                            <span
                                v-if="!disabled"
                                class="el-upload-list__item-delete"
                                @click="handleRemove(file)"
                            >
                                <el-icon><Delete /></el-icon>
                            </span>
                            </span>
                        </div>
                        </template>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="正文" >
                    <div style="border: 1px solid #ccc">
                    <Toolbar
                        style="border-bottom: 1px solid #ccc"
                        :editor="editorRef"
                        :defaultConfig="toolbarConfig"
                       
                    />
                    <Editor
                        style="height: 200px;width: 500px; ;overflow-y: hidden;"
                        v-model="ruleForm.content"
                        :defaultConfig="editorConfig"
                    
                        @onCreated="handleCreated"
                    />
                    </div>
                </el-form-item>      
                <el-form-item>
                    <el-button type="primary" @click="submit(ruleFormRef)">{{ routeMsg ?'修改':'添加' }}</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance ,FormRules } from 'element-plus'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {addnews ,onenews, upnews} from '../../api/admin3'
import { onBeforeUnmount, reactive,ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { UploadFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import {Trembling,throttle} from '../../utils/tool'
import {useRouter,useRoute} from 'vue-router';
const router = useRouter();
const ruleForm = reactive<any>({
    desc:'',
    title: "", 
    content: "<p></p>", 
    keywords: "", 
    thumb: "", 
    author: ""
})
const route = useRoute();
let routeMsg = ref<any>('');
if(route.query.newsid){      
    routeMsg = route.query.newsid ;
    console.log(routeMsg)
}
const getonelist=async()=>{
    const res:any=await onenews({id:routeMsg})
    console.log(res,'单挑')
    if(res.code==10000){
        Object.assign(ruleForm, res.data); 
        
    }
}


const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
})
const submit:any=Trembling(async ()=>{
    if(!ruleFormRef.value) return
    await ruleFormRef.value.validate(async(valid:any, fields:any) => {
        if (valid) {
                if(routeMsg){
                    let res:any=await upnews(ruleForm)
                    console.log(666, res)
                    if (res && res.code === 10000) {
                        ElMessage({
                            message: '修改成功',
                            type: 'success',
                        })
                        
                        // console.log(res)
                        router.push("/components-demo/tinymce");
                    } else {
                        ElMessage({
                            message: res.message,
                            type: 'error',
                        })
                    }
                }else{
                    let res: any = await addnews(ruleForm)
                    console.log(666, res)
                    if (res && res.code === 10000) {
                        ElMessage({
                            message: '添加成功',
                            type: 'success',
                        })
                        
                        // console.log(res)
                        router.push("/components-demo/tinymce");
                    } else {
                        ElMessage({
                            message: res.message,
                            type: 'error',
                        })
                    }
                }
           
        } else {
            console.log('error submit!', fields)
        }
    })
   
},300)



const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const handleRemove = (file: UploadFile) => {
  console.log(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}

  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef()
 
 // 内容 HTML
 const valueHtml = ref('<p>hello</p>')

 // 模拟 ajax 异步获取内容
 onMounted(() => {


     setTimeout(() => {
         valueHtml.value = '<p></p>'
     }, 1500)

     if(routeMsg){
        getonelist()
     }
 })

 const toolbarConfig = {}
 const editorConfig = { placeholder: '请输入内容...' }

 // 组件销毁时，也及时销毁编辑器
 onBeforeUnmount(() => {
     const editor = editorRef.value
     if (editor == null) return
     editor.destroy()
 })

 const handleCreated = (editor:any) => {
   editorRef.value = editor // 记录 editor 实例，重要！
 }
</script>

<style scoped lang="less">
.box{
    width: 100%;
    height: 100%;
    // background-color: rebeccapurple;
    border-top: 1px solid #fff;
    .title{
        width: 80px;
        height: 30px;
  
        // background-color: darkgoldenrod;
        font-weight: bold;
        font-size: 20px;
        margin-top: 20px;
        margin-left: 30px;
    }
    .frombox{
        margin-left: 30px;
        margin-top: 30px;
        width: 450px;
    }
}
</style>